package com.bringspring.common.database.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.util.DateUtil;
import com.bringspring.common.util.UserProvider;
import com.bringspring.common.util.context.SpringContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MybatisPlus配置类
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月27日 上午9:18
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {


    private UserProvider userProvider;

    @Override
    public void insertFill(MetaObject metaObject) {
        userProvider = SpringContext.getBean(UserProvider.class);
        UserInfo userInfo = userProvider.get();
        Object enabledMark = this.getFieldValByName("enabledMark", metaObject);
        Object creatorUserId = this.getFieldValByName("creatorUserId", metaObject);


        Object lastModifyUserId = this.getFieldValByName("lastModifyUserId", metaObject);
        if (ObjectUtils.isEmpty(enabledMark)) {
            this.setFieldValByName("enabledMark", 1, metaObject);
        }
        if (null != userInfo && ObjectUtils.isEmpty(creatorUserId)) {
            this.setFieldValByName("creatorUserId", userInfo.getUserId(), metaObject);
        }
        this.setFieldValByName("creatorTime", DateUtil.getNowDate(), metaObject);
        this.setFieldValByName("lastModifyTime", DateUtil.getNowDate(), metaObject);
        if (null != userInfo && ObjectUtils.isEmpty(lastModifyUserId)) {
            this.setFieldValByName("lastModifyUserId", userInfo.getUserId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        userProvider = SpringContext.getBean(UserProvider.class);
        UserInfo userInfo = userProvider.get();

        Object lastModifyUserId = this.getFieldValByName("lastModifyUserId", metaObject);
        this.setFieldValByName("lastModifyTime", DateUtil.getNowDate(), metaObject);
        if (null != userInfo && ObjectUtils.isEmpty(lastModifyUserId)) {
            this.setFieldValByName("lastModifyUserId", userInfo.getUserId(), metaObject);
        }

    }

}
